package Dao;

import demo523.SqlConnection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import static demo523.SqlConnection.getCon;

public class UserDao {
    Connection connection = SqlConnection.getCon();

    public UserDao() throws SQLException, ClassNotFoundException {
    }

    public int addUser(String username, String password) throws ClassNotFoundException, SQLException {

        Connection connection = getCon();
        String sql = "insert into users(username,password) values(?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, username);
        preparedStatement.setString(2, password);
        return preparedStatement.executeUpdate();

    }

    public Users login(String username, String password) throws ClassNotFoundException, SQLException {
        Users users = null;
        int i = 1;
        Connection connection = getCon();
        String sql = "select *feom users where username=? and password=?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, username);
        preparedStatement.setString(2, password);
        ResultSet resultSet = preparedStatement.executeQuery();

        if (resultSet.next()) {
            users = new Users();
            users.setId(resultSet.getInt("id"));
            users.setUsername(resultSet.getString("username"));
            users.setPassword(resultSet.getString("password"));
        }
        return users;
    }

    public int delete(int id) throws SQLException, ClassNotFoundException {
        String sql = "delete from users where id = ?";
        PreparedStatement preparedStatement = getCon().prepareStatement(sql);
        preparedStatement.setInt(1, id);
        return preparedStatement.executeUpdate();
    }

    public int deleteUser(int id) {
        String sql = "delete from users where id = ?";
        try {
            PreparedStatement preparedStatement = getCon().prepareStatement(sql);
            preparedStatement.setInt(1, id);
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return id;
    }
    public int updateUsers(int id, String username, String password) throws ClassNotFoundException, SQLException {
        Connection connection = SqlConnection.getConnection();
        String sql = "UPDATE users SET username = ?, password = ? WHERE id = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, username);
        preparedStatement.setString(2, password);
        preparedStatement.setInt(3, id);
        return preparedStatement.executeUpdate();
    }
}


